﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using SilverFernCheckerCore.Settings;
using Timer = System.Timers.Timer;
using SilverFernCheckerCore.Helpers;

namespace SilverFernWebSiteBotService
{
    public partial class SilverFernBotService : ServiceBase
    {
        private readonly Timer _timer;
        private readonly Settings _settings;
        
        private int _jobCounter=1;

        public SilverFernBotService()
        {
            InitializeComponent();
            _settings = new Settings();
            _timer = new Timer(_settings.RequestInterval);
            _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
        }

        void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                InitPeriodSettings();
                StartJob();
                //var th = new Thread(new ThreadStart(StartJob));
                //th.SetApartmentState(ApartmentState.STA);
                //th.Start();
                //th.Join();
            }
            catch(Exception ex)
            {
                Log("Service error: " + ex, LogType.Error);
            }
        }

        

        private void StartJob()
        {
            Log("Job #"+_jobCounter+" starting...", LogType.Message);
            var _worker = new Worker();
            
            var result = _worker.MakeJob();
            switch (result.Type)
            {
                case LogType.QuotaFounded:
                    Log(result.Message, LogType.QuotaFounded);
                    if (_settings.NotificationViaEmail) _worker.SendEmail(result.Message);
                    if (_settings.NotificationViaSms) _worker.SendSms(result.Message);
                            if (!string.IsNullOrWhiteSpace(_settings.CustomActionFilePath))
                                _worker.OpenFile(_settings.CustomActionFilePath);
                        break;
                    case LogType.Error:
                        Log(result.Message, LogType.Error);
                        break;
                    default:
                        Log(result.Message, LogType.Message);
                        break;
            }
            Log("Job #" + _jobCounter + " ended", LogType.Message);
            Log("Job #" + (++_jobCounter) + " started after " + _timer.Interval / 1000/60 + " min.", LogType.Message);
        }

        private void InitPeriodSettings()
        {
            if (_settings.RequestInterval != _timer.Interval)
                _timer.Interval = _settings.RequestInterval;
        }

        protected override void OnStart(string[] args)
        {
            _timer.Start();
            Log("Service started", LogType.Message);
            Log("Job #" + (_jobCounter) + " will start after " + _timer.Interval / 1000/60 + " min.", LogType.Message);
        }


        void Log(string mess, LogType type)
        {

            try
            {
                if (!EventLog.SourceExists(_settings.EventLogName))
                {
                    EventLog.CreateEventSource(_settings.EventLogName, _settings.EventLogName);
                }
                eventLog1.Source = _settings.EventLogName;
                switch(type)
                {
                    case LogType.Error:
                        eventLog1.WriteEntry(mess,EventLogEntryType.Error);
                        break;
                    case LogType.QuotaFounded:
                        eventLog1.WriteEntry(mess, EventLogEntryType.Warning);
                        break;
                    default:
                        eventLog1.WriteEntry(mess);
                        break;
                }
            }
            catch { }
            
        }

        protected override void OnStop()
        {
            _timer.Stop();
            Log("Service stoped", LogType.Message);
        }
    }
}
